package com.jwgf.printprotocolstack;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.util.Log;

public class PrintUtils {
	public static byte[] createPrintFrame(String data) {
		ArrayList<Integer> encode = new ArrayList<Integer>();
		for (int i = 0; i < data.length(); i++) {
			if (isASCIICharacter(data.charAt(i))) {
				int ascii = data.charAt(i);
				encode.add(ascii);
			} else {
				String result = "";
				try {
					result = URLEncoder.encode(String.valueOf(data.charAt(i)), "GB2312");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				String[] gb = result.split("%");
				for (String s : gb) {
					try {
						if (!s.equals("")) {
							int gb2312 = Integer.parseInt(s, 16);
							encode.add(gb2312);
						}
					} catch (Exception e) {
						e.printStackTrace();
						Log.e("String_Encorde", "parse gb2312 number error:" + e.toString());
					}

				}
			}
		}
		encode.add(0x0d);

		byte[] printEncode = new byte[encode.size() + 2];
		printEncode[0] = (byte) (encode.size() + 1);
		for (int i = 0; i < encode.size(); i++) {
			printEncode[i+1] = (byte) encode.get(i).intValue();
		}
		printEncode[printEncode.length - 1] = bcc8(printEncode);
		return printEncode;
	}

	public static byte bcc8(byte[] data) {
		int bcc = 0;
		for (byte b : data) {
			int temp = b & 0xff;
			bcc ^= temp;
		}
		return (byte) (bcc & 0xff);
	}

	public static boolean isASCIICharacter(char input) {
		String compareChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .*-_/\\:;";
		if (compareChar.contains(String.valueOf(input)))
			return true;
		else
			return false;
	}
}
